package hjw.com.controller.adm;

import hjw.com.dao.ClzMapper;
import hjw.com.dao.LargeFileMapper;
import hjw.com.dao.UserMapper;
import hjw.com.entity.Clz;
import hjw.com.entity.LargeFile;
import hjw.com.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Controller
@RequestMapping("/adm/stu")
@SuppressWarnings("all")
public class AdmStuController {

    @Autowired
    UserMapper um;
    @Autowired
    ClzMapper clzMapper;
    @Autowired
    LargeFileMapper lfd;

    //role必须为tea、stu、adm

    @RequestMapping({"/prevPage","/nextPage","/show"})
    public String prevPage(Integer curPage, Model model){
        final int pageSize = 5;//设置固定的每页显示数量
        Integer start = 1;
        if (curPage == null) curPage = 1;//初始化页数
        Integer count = um.count("stu");//数据库含有的数据的总行数
        Integer totalPage = count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1;//计算出最大页数

        System.out.println(totalPage);
        if (curPage > totalPage) curPage = totalPage;//限制显示页数不能大于总行数
        if (curPage != null) start = curPage;//获取每页提交过来的页码并赋值

        String s = String.valueOf(pageSize);
        Map<String,Object> map = new HashMap<>();
        map.put("start",(start-1) * pageSize);
        map.put("pageSize",pageSize);
        map.put("role","stu");
        List<User> users = um.findByLine(map);
        System.out.println(curPage);
        List<Clz> clzs = clzMapper.findAll();

        model.addAttribute("curPage",start);//设置当前页数
        model.addAttribute("totalPage",totalPage);//设置计算出最大页数
        model.addAttribute("users",users );//设置当前页内容
        model.addAttribute("user",new User());
        model.addAttribute("clzs",clzs);//设置当前页内容

        model.addAttribute("action","stu");
        return "adm/show";
    }

    //获取图片信息的头路径
    @RequestMapping("/showimg/{id}")
    public void show(@PathVariable("id")String id, HttpServletResponse resp, Model model){
        LargeFile one = lfd.findOne(id);
        if (one == null)return;
        byte[] buf = (byte[]) one.getContent();
        try {
            OutputStream os = resp.getOutputStream();
            resp.setContentType("image/jpeg");
            os.write(buf);
            os.flush();//刷新资源
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/go2Add/{curPage}")
    public String go2Add(@PathVariable ("curPage")Integer curPage,Model model){
        return "forward:/adm/stu/prevPage?curPage=" + curPage;
    }

    @PostMapping("/doAdd")
    public String doAdd(User user, MultipartFile mypic, Integer curPage, Model model){
        System.out.println(curPage);
        //获取上传文件的名称
        String saveFileName = mypic.getOriginalFilename();
        //获取唯一id
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-","");
        //写入pic的id
        user.setPic(uuid);
        if (saveFileName.length() > 0){
            LargeFile largeFile = new LargeFile();
            largeFile.setId(uuid);
            largeFile.setFilename(saveFileName);
            try {
                largeFile.setContent(mypic.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            //将图片写入数据库
            lfd.add(largeFile);
        }
        user.setRole("stu");
        int key = 0;
        System.out.println(user);
        try {
            //写入数据库
            key = um.add(user);
        } catch (Exception e) {
            model.addAttribute("state",key > 0 ? "：添加成功":"：添加失败(手机号已存在)");
        }
        model.addAttribute("state",key > 0 ? "：添加成功":"：添加失败");
        return "forward:/adm/stu/prevPage?curPage=" + curPage;
    }

    @GetMapping("/go2Update")
    public String go2Update(String uid,String curPage, Model model){
        User stu = um.findByUid(uid, "stu");
        model.addAttribute("date","doUpdate");
        model.addAttribute("uid", stu.getUid());
        model.addAttribute("uname",stu.getUname());
        model.addAttribute("phone",stu.getPhone());
        model.addAttribute("pwd",stu.getPwd());
        model.addAttribute("pic",stu.getPic());
        return "forward:/adm/stu/prevPage?curPage=" + curPage;
    }

    @PostMapping("/doUpdate")
    public String doUpdate(User user , MultipartFile mypic, Integer curPage, Model model){
        //获取上传文件的名称
        String saveFileName = mypic.getOriginalFilename();
        System.out.println("saveFileName = " + saveFileName);
        if (mypic.getOriginalFilename().length() > 0){
            //获取用户pic的id
            String pic = um.findByUid(user.getUid(), "stu").getPic();

            lfd.delete(pic);

            LargeFile largeFile = new LargeFile();
            largeFile.setId(pic);
            largeFile.setFilename(saveFileName);
            try {
                largeFile.setContent(mypic.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            //修改数据库照片
            lfd.add(largeFile);
        }

        int key = 0;//修改用户信息
        try {
            key = um.updateById(user);
        } catch (Exception e) {

        }
        model.addAttribute("state",key > 0 ? "：修改成功":"：修改失败");
        return "forward:/adm/stu/prevPage?curPage=" + curPage;
    }

    @GetMapping("/del")
    public String dodel(String uid, Integer curPage, Model model){
        lfd.delete(um.findByUid(uid,"stu").getPic());
        int key = um.delById(uid);
        model.addAttribute("state",key > 0 ? "：删除成功":"：删除失败");
        return "forward:/adm/stu/prevPage?curPage=" + curPage;
    }


}
